package com.example.park_management.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.park_management.common.PageParam;
import com.example.park_management.common.Result;
import com.example.park_management.domain.*;
import com.example.park_management.domain.vo.LoginResultVO;
import com.example.park_management.service.ComplaintsService;
import com.example.park_management.service.ExpensesService;
import com.example.park_management.service.OwnersService;
import com.example.park_management.service.ParkingSpacesService;
import com.example.park_management.util.JwtUtil;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/owners")
public class OwnersController {
    @Value("${config.shiro.secret}")
    private String secret;

    @Resource
    OwnersService ownersService;

    @Resource
    ComplaintsService complaintsService;

    @Resource
    ParkingSpacesService parkingSpacesService;

    @Resource
    ExpensesService expensesService;
    @PostMapping("/login")
    Result ownersLogin(@RequestBody Owners owners){
        Owners one = ownersService.getOne(new QueryWrapper<Owners>().eq("username", owners.getUsername()).eq("password", owners.getPassword()));
        if (one != null){
            LoginResultVO loginResultVO = new LoginResultVO();
            loginResultVO.setUsername(one.getUsername());
            loginResultVO.setUsername(one.getPassword());
            loginResultVO.setToken(JwtUtil.sign(one.getOwnerId().toString(),secret,"owners"));
            return Result.success(loginResultVO);
        }
        return Result.fail("账号或密码错误");
    }


    @PostMapping("/register")
    Result register(@RequestBody Owners owners){
        if (StringUtils.isBlank(owners.getUsername()) || StringUtils.isBlank(owners.getPassword()) || StringUtils.isBlank(owners.getIdNumber())) {
            return Result.fail("必填属性为空");
        }
        Owners one = ownersService.getOne(new QueryWrapper<Owners>().eq("username", owners.getUsername()));
        if (one != null){
            return Result.fail("用户名已存在");
        }
        ownersService.save(owners);
        return Result.success();
    }

    @DeleteMapping("/{ownerId}")
    public Result delete(@PathVariable Integer ownerId) {
        //检验业主下面是否有投诉、费用、车位，若有提示不允许删除业主应先删除相关数据
        LambdaQueryWrapper<Complaints> queryWrapper1 = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Expenses> queryWrapper2 = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<ParkingSpaces> queryWrapper3 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Complaints::getComplaintId,ownerId);
        queryWrapper2.eq(Expenses::getExpenseId,ownerId);
        queryWrapper3.eq(ParkingSpaces::getSpaceId,ownerId);
        List<Complaints> list1 = complaintsService.list(queryWrapper1);
        List<Expenses> list2 = expensesService.list(queryWrapper2);
        List<ParkingSpaces> list3 = parkingSpacesService.list(queryWrapper3);
        if (!CollectionUtils.isEmpty(list1) && !CollectionUtils.isEmpty(list2)&& !CollectionUtils.isEmpty(list3)){
            //String fStr = list1.stream().map(f -> f.getComplaintId().toString()).collect(Collectors.joining());
            return Result.fail("删除失败,请先删除业主的相关信息！！");
        }
        boolean b = ownersService.removeById(ownerId);
        if (b){
            return Result.success();
        }
        return Result.fail();
    }

    @PutMapping("/")
    public Result update(@RequestBody Owners owners) {
        try{
            if (StringUtils.isBlank(owners.getUsername()) || StringUtils.isBlank(owners.getPassword()) ) {
                return Result.fail("必填属性为空");
            }
            if (ownersService.updateById(owners)){
                return Result.success();
            }
            return Result.fail();
        }catch (Exception e) {
            return Result.fail("输入格式异常！");
        }
    }

    @PostMapping("/page")
    public Result page(@RequestBody PageParam<Owners> pageParam) {
        Page<Owners> ownersPage = new Page<>(pageParam.getPageNum(), pageParam.getPageSize());


        QueryWrapper<Owners> ownersQueryWrapper = new QueryWrapper<>();
        if (pageParam.getData() != null) {
            if (pageParam.getData().getUsername() != null) {
                ownersQueryWrapper.like("username", pageParam.getData().getUsername());
            }
            if (pageParam.getData().getRealName() != null) {
                ownersQueryWrapper.like("real_name", pageParam.getData().getRealName());
            }
            if (pageParam.getData().getPhoneNumber() != null) {
                ownersQueryWrapper.like("phone_number", pageParam.getData().getPhoneNumber());
            }
        }
        ownersService.page(ownersPage,ownersQueryWrapper);

        return Result.success(ownersPage.getRecords(),ownersPage.getTotal());
    }


}
